import java.util.Arrays;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25397
 * Date: 2022-02-26
 * Time: 14:24
 */
public class HashBuck3<K,V> {//泛型的哈希
    static class Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;
        public Node(K key,V value){
            this.key=key;
            this.val=value;
        }
    }
    public Node<K,V>[]arr=(Node<K,V>[])new Node[10];
    public int usedSize;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashBuck3<?, ?> hashBuck3 = (HashBuck3<?, ?>) o;
        return usedSize == hashBuck3.usedSize && Arrays.equals(arr, hashBuck3.arr);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(usedSize);
        result = 31 * result + Arrays.hashCode(arr);
        return result;
    }

    public void put(K key, V value){
        int hash=key.hashCode();
        int index=hash%arr.length;

        Node cur=arr[index];
        while(cur!=null){
            if(cur.key.equals(key)){//这里不能用==比较（引用类型用equals比较）,euqals用之前也要重写一下
                //ps:每次自己生成的hashcode一样，但是equals不一定一样
                //如果equals一样，hashcode一定一样
                cur.val=value;
                return;
            }
            cur=cur.next;
        }

        Node<K,V> node=new Node(key, value);
        node.next=arr[index];
        arr[index]=node;
        this.usedSize++;
    }

    public V get(K key){
        int hash= key.hashCode();
        int index=hash%arr.length;
        Node<K,V> cur=arr[index];
        while(cur!=null){
            if(cur.key.equals(key)){
                return cur.val;
            }
            cur=cur.next;
        }
        return null;
    }

    public static void main(String[] args) {
        Person p1=new Person("1");
        Person p2=new Person("1");
        HashBuck3<Person,String> hashBuck3=new HashBuck3<>();
        hashBuck3.put(p1,"wxy");
        System.out.println(hashBuck3.get(p2));//打印wxy
    }
}
